<template>
  <div class="app-container">
    <el-form ref="noticedemandapprovalRef" :model="formData" :rules="rules" label-width="140px">
      <el-row :gutter="20">
        <el-col :span="9">
          <el-form-item label="立案号" prop="caseId">
            <el-select
              v-model="formData.caseId"
              placeholder="请选择立案号"
              :disabled="disabled || isFlow"
              clearable
              @change="handleCase">
              <el-option v-for="item in numberList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="当事人名称" prop="partyName">
            <el-input v-model="formData.partyName" disabled placeholder="请输入当事人名称" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="法定代表人" prop="legalRepresentative">
            <el-input v-model="formData.legalRepresentative" disabled placeholder="请输入法定代表人" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="营业执照类型" prop="businessType">
            <el-input v-model="formData.businessType" disabled placeholder="请输入营业执照类型" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="统一社会信用代码" prop="unifiedSocialCreditCode">
            <el-input v-model="formData.unifiedSocialCreditCode" disabled placeholder="请输入统一社会信用代码" />
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="地址" :rules="rules.addressObj" prop="addressObj">
            <locationSelect v-model="formData.addressObj" disabled style="width: 100%" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <CaseSituation
          ref="caseSituationRef"
          v-model="formData"
          :disabled="disabled"
          :isFlow="isFlow"
          :show="'案情说明, 证据证明, 违反条例, 处理依据'"
          :caseIsEdit="true"
          :isEdit="true"
          :reasonDisabled="true"
          :violationIsEdit="true" />
      </el-row>
    </el-form>
  </div>
</template>

<script setup>
import { ref, getCurrentInstance, watch, onBeforeUnmount } from 'vue'
import {
  getcompulsoryrectify,
  addcompulsoryrectify,
  updatecompulsoryrectify,
  getCaseList,
  getContent,
  previewPdf,
} from '@/api/orderRectification/index.js'
import { registrationcaseDetail } from '@/api/filingReview/register'
import { ElMessage } from 'element-plus'
import locationSelect from '@/components/locationSelect/index.vue'
import CaseSituation from '@/components/CaseSituation/index.vue'
import { useRouter } from 'vue-router'

const { proxy } = getCurrentInstance()

// Props
const props = defineProps({
  id: {
    type: [String, Number],
    default: null,
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  isFlow: {
    type: Boolean,
    default: false,
  },
})

const router = useRouter()

// Emits
const emit = defineEmits(['handleSubmit'])

// Form data
const formData = ref({
  id: null,
  caseId: null,
  caseNo: null,
  decisionsId: null,
  demandYear: null,
  demandSerialNo: null,
  demandNo: null,
  partyName: null,
  streetOfCompanyAddress: null,
  address: null,
  unifiedSocialCreditCode: null,
  legalRepresentative: null,
  approvalItem: null,
  noticeDate: null,
  caseDesc: null,
  evidenceDesc: null,
  violationRegulations: null,
  handlingBasis: null,
  teamLeaderOpinion: null,
  legalHandlerOpinion: null,
  legalLeaderHandlerOpinion: null,
  handlerLeaderOpinion: null,
  remark: null,
  applyTime: null,
  status: null,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null,
  delFlag: null,
})
// 自定义校验器：检查拍摄地点是否完整
const validateLocation = (rule, value, callback) => {
  if (!value || !value.streetOfPhotoLocation || !value.photoLocation) {
    callback(new Error('请选择地点'))
  } else {
    callback()
  }
}
// Form validation rules
const rules = {
  caseNo: [{ required: true, message: '立案号不能为空', trigger: ['blur', 'change'] }],
  partyName: [{ required: true, message: '当事人名称不能为空', trigger: ['blur', 'change'] }],
  caseDesc: [{ required: true, message: '请输入案情说明', trigger: ['blur', 'change'] }],
  evidenceDesc: [{ required: true, message: '请输入证据证明', trigger: ['blur', 'change'] }],
  violationRegulations: [{ required: true, message: '请输入违反条例', trigger: ['blur', 'change'] }],
  handlingBasis: [{ required: true, message: '请输入处理依据', trigger: ['blur', 'change'] }],
  caseId: [{ required: true, message: '立案号不能为空', trigger: ['blur', 'change'] }],
  partyName: [{ required: true, message: '当事人名称不能为空', trigger: ['blur', 'change'] }],
  legalRepresentative: [{ required: true, message: '法定代表人不能为空', trigger: ['blur', 'change'] }],
  businessType: [{ required: true, message: '营业执照类型不能为空', trigger: ['blur', 'change'] }],
  unifiedSocialCreditCode: [{ required: true, message: '统一社会信用代码不能为空', trigger: ['blur', 'change'] }],
  addressObj: [{ required: true, validator: validateLocation, trigger: ['blur', 'change'] }],
  approvalItem: [{ required: true, message: '审批事项不能为空', trigger: ['blur', 'change'] }],
}

// Refs
const noticedemandapprovalRef = ref()

// Methods
const reset = () => {
  formData.value = {
    id: null,
    caseId: null,
    caseNo: null,
    decisionsId: null,
    demandYear: null,
    demandSerialNo: null,
    demandNo: null,
    partyName: null,
    streetOfCompanyAddress: null,
    address: null,
    unifiedSocialCreditCode: null,
    legalRepresentative: null,
    approvalItem: null,
    noticeDate: null,
    caseDesc: null,
    evidenceDesc: null,
    violationRegulations: null,
    handlingBasis: null,
    teamLeaderOpinion: null,
    legalHandlerOpinion: null,
    legalLeaderHandlerOpinion: null,
    handlerLeaderOpinion: null,
    remark: null,
    applyTime: null,
    status: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null,
  }
  proxy.resetForm('noticedemandapprovalRef')
}

// Get detail data
const getDetail = async id => {
  reset()
  if (id) {
    try {
      const res = await getcompulsoryrectify(id)
      if (!res?.data) return
      formData.value = res.data
      formData.value.addressObj = {
        photoLocation: res.data.address,
        streetOfPhotoLocation: res.data.streetOfCompanyAddress,
      }
    } catch (error) {
      console.error('获取详情失败:', error)
    }
  }
}

const handleCase = async val => {
  return new Promise(async (resolve, reject) => {
    if (!val) {
      formData.value.caseNo = ''
      formData.value.decisionsId = ''
      formData.value.partyName = ''
      formData.value.partyId = ''
      formData.value.legalRepresentative = ''
      formData.value.businessType = ''
      formData.value.unifiedSocialCreditCode = ''
      formData.value.evidenceDesc = ''
      formData.value.addressObj = {
        photoLocation: '',
        streetOfPhotoLocation: '',
      }
      return
    }
    const res = await registrationcaseDetail(val)
    const { partyName, partyId, legalRepresentative, unifiedSocialCreditCode, streetOfCompanyAddress, address } =
      res.data
    formData.value.caseNo = res.data.caseNo
    formData.value.partyName = partyName
    formData.value.partyId = partyId
    formData.value.legalRepresentative = legalRepresentative
    formData.value.businessType = res.data.businessType
    formData.value.unifiedSocialCreditCode = unifiedSocialCreditCode
    formData.value.addressObj = {
      photoLocation: address,
      streetOfPhotoLocation: streetOfCompanyAddress,
    }
    const res2 = await getContent(val)
    formData.value.caseDesc = res2.data.caseDesc
    formData.value.violationRegulations = res2.data.violationRegulations
    formData.value.evidenceDesc = res2.data.evidenceDesc
    resolve()
  })
}

const handlePreview = () => {
  return new Promise(resolve => {
    submitForm(true)
      .then(async params => {
        previewPdf(params)
          .then(res => {
            if (!!res.msg) {
              window.open(res.msg)
              resolve()
            } else {
              ElMessage.warning('预览文件不存在')
              resolve()
            }
          })
          .catch(() => {
            ElMessage.warning('预览文件不存在')
            resolve()
          })
      })
      .catch(() => {
        ElMessage.warning('请先完善表单信息')
        resolve()
      })
  })
}

// Submit form
const caseSituationRef = ref(null)
const submitForm = (isPreview = false) => {
  return new Promise(async (resolve, reject) => {
    noticedemandapprovalRef.value
      .validate()
      .then(async () => {
        if (isPreview === true) {
          resolve(formData.value)
          return
        }
        formData.value.address = formData.value.addressObj.photoLocation
        formData.value.streetOfCompanyAddress = formData.value.addressObj.streetOfPhotoLocation
        let result = null
        if (formData.value.id) {
          result = await updatecompulsoryrectify(formData.value)
        } else {
          result = await addcompulsoryrectify(formData.value)
        }

        ElMessage.success('提交成功')
        emit('handleSubmit', result)
        return result
      })
      .catch(error => {
        console.error('表单验证失败:', error)
        reject(error)
      })
  })
}

// Watch props.id change
watch(
  () => props.id,
  newVal => {
    if (newVal) {
      getDetail(newVal)
    } else {
      reset()
    }
    handleCaseList()
  },
  { immediate: true }
)

const numberList = ref([])
async function handleCaseList() {
  const res = await getCaseList()
  numberList.value = res.data.map(item => ({
    label: item.caseNo,
    value: item.id,
  }))
}
onBeforeUnmount(() => {})
// Expose methods
defineExpose({
  submitForm,
  handlePreview,
  reset,
  formData,
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}
</style>
